<template>
  <div>
    <!-- 搜索门店报备信息条件 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="上传日期">
          <el-date-picker
            v-model="searchModel.createDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchModel.state" placeholder="请选择">
            <el-option label="全部" :value="null" />
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核不通过" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="一级代理商名称">
          <el-input
            v-model.trim="searchModel.firstMasterName"
            placeholder="请输入一级代理商名称"
          />
        </el-form-item>
        <el-form-item label="一级代理商ID">
          <el-input
            v-model.trim="searchModel.firstMasterId"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
            placeholder="请输入一级代理商ID"
          />
        </el-form-item>
        <el-form-item label="展业员名称">
          <el-input
            v-model.trim="searchModel.agentName"
            placeholder="请输入展业员名称"
          />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model.trim="searchModel.userMobile"
            placeholder="请输入手机号码"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" color="#ea5b24" @click="searchAudit()"
            >查询</el-button
          >
          <el-button
            type="primary"
            color="#ea5b24"
            @click="exportStorefront()"
            v-if="pinia.isShow[69]"
            >导出Excel</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 门店报备数据列表 -->
    <div>
      <el-table :data="tableData.data" style="width: 100%; margin-top: 20px">
        <el-table-column
          prop="firstMasterId"
          width="110"
          label="一级代理商ID"
        />
        <el-table-column
          prop="firstMasterName"
          width="130"
          label="一级代理商名称"
        />
        <el-table-column prop="agentId" label="展业员ID" />
        <el-table-column prop="group" label="部门名称" />
        <el-table-column prop="agentName" width="100" label="展业员姓名" />
        <el-table-column prop="userMobile" width="120" label="手机号码" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="city" label="城市" />
        <el-table-column prop="county" label="区县" />
        <el-table-column prop="address" width="160" label="详细地址" />
        <el-table-column prop="licensePictureUrl" label="营业执照">
          <template #default="scope">
            <el-button
              link
              type="text"
              size="small"
              @click="imgDialogShow(scope.row, 1)"
            >
              {{ scope.row.licensePictureUrl ? "查看" : null }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="doorPictureUrl" label="门头照">
          <template #default="scope">
            <el-button
              link
              type="text"
              size="small"
              @click="imgDialogShow(scope.row, 2)"
            >
              {{ scope.row.doorPictureUrl ? "查看" : null }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="indoorPictureUrl" label="室内照">
          <template #default="scope">
            <el-button
              link
              type="text"
              size="small"
              @click="imgDialogShow(scope.row, 3)"
            >
              {{ scope.row.indoorPictureUrl ? "查看" : null }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="idCardFrontPhoto"
          width="70"
          label="身份证正面照"
        >
          <template #default="scope">
            <el-button
              link
              type="text"
              size="small"
              @click="imgDialogShow(scope.row, 4)"
            >
              {{ scope.row.idCardFrontPhoto ? "查看" : null }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="idCardBackPhoto" width="70" label="身份证背面照">
          <template #default="scope">
            <el-button
              link
              type="text"
              size="small"
              @click="imgDialogShow(scope.row, 5)"
            >
              {{ scope.row.idCardBackPhoto ? "查看" : null }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="idCardNumber" width="170" label="身份证号码" />
        <el-table-column
          prop="auditInfoCreateTime"
          width="160"
          label="上传日期"
        />
        <el-table-column prop="auditTime" width="160" label="审核日期" />
        <el-table-column
          prop="state"
          width="100"
          :formatter="judgeState"
          label="状态"
        />
        <el-table-column prop="reason" width="140" label="原因" />
        <el-table-column prop="note" width="140" label="备注" />
        <el-table-column fixed="right" width="140" label="操作">
          <template v-slot:default="scope">
            <!-- <div v-if="scope.row.state === 0"></div> -->
            <el-button
              link
              type="primary"
              size="small"
              @click="examineDialog(scope.row, 1)"
              v-if="pinia.isShow[68]"
              >审核</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="examineDialog(scope.row, 2)"
              v-if="pinia.isShow[100]"
              >审核不通过</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="locationDialog(scope.row)"
              v-if="pinia.isShow[70]"
              >查看登录地</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="syncData(scope.row.auditId)"
              v-if="pinia.isShow[176]"
              >第三方上报</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>

    <!-- 审核dialog -->
    <el-dialog
      v-model="examineDialogVisible"
      title="审核"
      center="true"
      modal="true"
      width="470px"
    >
      <el-form :model="examineParam">
        <el-form-item label="审核状态:">
          <el-radio-group v-model="examineParam.state">
            <el-radio :label="0" v-if="examineNoPass">待审核</el-radio>
            <el-radio :label="1" v-if="examineNoPass">审核通过</el-radio>
            <el-radio :label="2">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原因">
          <el-input
            v-model.trim="examineParam.reason"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 3 }"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" color="#ea5b24" @click="examineReview()"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 图片展示dialog -->
    <el-dialog
      v-model="imgDialog"
      :title="imgTitle"
      width="500px"
      :visible.sync="dialogVisible"
      draggable
      center
      :show-close="false"
    >
      <div>
        <el-image
          :src="imgUrl"
          :preview-src-list="srcList"
          style="width: 100%"
        />
      </div>
    </el-dialog>
    <!-- <el-image style="width: 60px; height: 60px" :src="url" :zoom-rate="1.2" :preview-src-list="srcList"
            :initial-index="4" fit="contain" /> -->
    <!-- <el-image-viewer v-if="dialogVisible" :on-close="closeImg" :url-list="srcList" /> -->

    <!-- 查看登陆地dialog -->
    <el-dialog
      v-model="locationDialogVisible"
      draggable
      center="true"
      modal="true"
      width="1200px"
    >
      <el-text class="span-location" size="large"
        >常用所在城市：{{ cityStr }}</el-text
      >
      <el-table
        :data="locationTableData.data"
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column prop="loginTime" width="100" label="登录时间" />
        <el-table-column prop="endpoint" label="登录端" />
        <el-table-column prop="ip" label="登录IP" />
        <el-table-column prop="longitude" label="经度" />
        <el-table-column prop="latitude" label="纬度" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="city" label="城市" />
        <el-table-column prop="district" label="区县" />
        <el-table-column prop="address" label="详细地址" />
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="locationTotalNum"
          small
          @current-change="locationHandleCurrentChange"
          background
          :page-size="locationSize"
          layout="prev, pager, next, total"
          :current-page="locationPage"
        />
      </div>
    </el-dialog>

    <!-- 第三方报备列表dialog -->
    <el-dialog
      v-model="agentDialogVisible"
      draggable
      center="true"
      modal="true"
      width="1200px"
    >
      <el-table
        :data="agentTableData.data"
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column prop="agentThirdPartyReportId" label="ID" />
        <el-table-column prop="auditId" label="审计信息id" />
        <el-table-column prop="createTime" width="160" label="首次申请时间" />
        <el-table-column
          prop="offlineChannelId"
          width="140"
          label="第三方线下通道id"
        />
        <el-table-column
          prop="onlineChannelId"
          width="140"
          label="第三方线上通道id"
        />
        <el-table-column
          width="90"
          prop="reportMsg"
          label="审核原因(第三方的)"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="reportStatus"
          :formatter="judgeReportStatus"
          label="审核状态"
        />
        <el-table-column prop="thirdPartyId" label="第三方id" />
        <el-table-column
          prop="thirdPartyType"
          :formatter="judgeThirdPartyType"
          label="第三方类型"
        />
        <el-table-column fixed="right" label="操作">
          <template v-slot:default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="escalation(scope.row)"
              v-if="
                (scope.row.reportStatus == 0 || scope.row.reportStatus == 3) &&
                pinia.isShow[177]
              "
              >{{
                scope.row.reportStatus == 0 ? "上报" : "重新上报"
              }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, rowContextKey } from "element-plus";
import {
  findStorefrontApi,
  examineReviewApi,
  findStorefrontExcelApi,
  findStoreAuditInfoApi,
  reportApplyApi,
  findAgentReportListApi,
} from "../../../api/index";
import { formatDateTime } from "../../../utils/formatDateTime";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 登陆地列表数据
let locationTableData: any = reactive([]);
const locationTotalNum = ref(0);
const locationPage = ref(1);
const locationSize = 8;
// 常住城市文字
const cityStr = ref();

const dialogVisible = ref(false);
// 登陆地展示dialog控制
const locationDialogVisible = ref(false);
// 审核dialog控制
const examineDialogVisible = ref(false);
// 审核不通过
const examineNoPass = ref(true);
// 照片dialog控制
const imgDialog = ref(false);
let imgTitle = ref("");
let imgUrl = ref();
let srcList = reactive([]);
// 第三方报备列表dialog控制
const agentDialogVisible = ref(false);
let agentTableData: any = reactive([]);
let currentAuditId = null;

// 审核参数
const examineParam = reactive({
  id: null,
  state: null,
  reason: null,
});

// 打开审核dialog
const examineDialog = (row, type: number) => {
  if (type === 1) examineNoPass.value = true;
  if (type === 2) examineNoPass.value = false;
  examineParam.id = row.auditId;
  examineParam.state = null;
  examineParam.reason = null;
  examineDialogVisible.value = true;
};

// 打开登陆地展示dialog
const locationDialog = (row) => {
  locationDialogVisible.value = true;
  locationModel.agentId = row.agentId;
  findAuditInfo();
};

// 条件搜索登陆地
const findAuditInfo = () => {
  findStoreAuditInfoApi(locationModel).then((res) => {
    if (res.data.code === 2000) {
      locationTableData.data = res.data.data.record.data;
      locationTotalNum.value = res.data.data.record.total;

      cityStr.value = "";
      res.data.data.usualCities.forEach((val, index) => {
        if (index === 0) {
          cityStr.value += val;
        } else {
          cityStr.value += "," + val;
        }
      });
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 过滤状态显示
const judgeState = (row) => {
  switch (row.state) {
    case 0:
      return "待审核";
    case 1:
      return "审核通过";
    case 2:
      return "审核不通过";
    default:
      return "错误";
  }
};

// 过滤审核状态显示
const judgeReportStatus = (row) => {
  switch (row.reportStatus) {
    case 0:
      return "未上报";
    case 1:
      return "审核中";
    case 2:
      return "审核成功";
    case 3:
      return "审核失败";
    default:
      return "错误";
  }
};

// 过滤第三方类型显示
const judgeThirdPartyType = (row) => {
  switch (row.thirdPartyType) {
    case 1:
      return "智通";
    default:
      return "错误";
  }
};

// 搜索模型
const searchModel: any = reactive({
  agentName: null,
  firstMasterId: null,
  firstMasterName: null,
  state: null,

  createDate: null,
  endAuditInfoCreateTime: null,
  endAuditTime: null,

  page: page,
  size: size,
});

// 查询登陆地条件
let locationModel = reactive({
  agentId: null,
  page: locationPage,
  size: locationSize,
});

// 翻页
let flipData = reactive({
  page: page,
  size: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.page = page.value;
  findStorefront(flipData);
};

// 登陆地数据翻页
const locationHandleCurrentChange = (val: number) => {
  locationPage.value = val;
  findAuditInfo();
};

// 搜索提现订单
const searchAudit = () => {
  page.value = 1;
  if (searchModel.createDate) {
    searchModel.startAuditInfoCreateTime = formatDateTime(
      searchModel.createDate[0]
    );
    searchModel.endAuditInfoCreateTime = formatDateTime(
      searchModel.createDate[1]
    ).replace("00:00:00", "23:59:59");
  } else {
    searchModel.startAuditInfoCreateTime = null;
    searchModel.endAuditInfoCreateTime = null;
  }
  searchParmSearch();
  findStorefront(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

// 查询门店数据
const findStorefront = (searchModel) => {
  findStorefrontApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.data;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 点击查看照片
const imgDialogShow = (row, type: number) => {
  imgDialog.value = true;
  if (type === 1) {
    imgTitle.value = "营业执照";
    imgUrl.value = row.licensePictureUrl;
  }
  if (type === 2) {
    imgTitle.value = "门头照";
    imgUrl.value = row.doorPictureUrl;
  }
  if (type === 3) {
    imgTitle.value = "室内照";
    imgUrl.value = row.indoorPictureUrl;
  }
  if (type === 4) {
    imgTitle.value = "身份证正面照";
    imgUrl.value = row.idCardFrontPhoto;
  }
  if (type === 5) {
    imgTitle.value = "身份证背面照";
    imgUrl.value = row.idCardBackPhoto;
  }
  srcList.length = 0;
  srcList.push(imgUrl.value);
};

// 审核
const examineReview = () => {
  if (examineParam.state == null) {
    ElMessage.error("请选择审核状态.");
    return;
  }
  if (
    examineParam.state == 2 &&
    (examineParam.reason == "" || examineParam.reason == null)
  ) {
    ElMessage.error("请输入不通过原因.");
  } else {
    examineReviewApi(examineParam).then((res) => {
      if (res.data.code === 2000) {
        ElMessage({
          message: "审核成功.",
          type: "success",
        });
      } else {
        ElMessage.error("审核失败.");
      }
      examineDialogVisible.value = false;
      findStorefront(searchModel);
    });
  }
};

// 打开登陆地展示dialog
const syncData = (auditId) => {
  agentDialogVisible.value = true;
  currentAuditId = auditId;
  findAgentReportListApi({ auditId: auditId }).then((res) => {
    if (res.data.code === 2000) {
      agentTableData.data = res.data.data;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 向第三方上报
const escalation = (row) => {
  reportApplyApi({ auditId: row.auditId, thirdPartyType: 1 }).then((res) => {
    if (res.data.code === 2000) {
      ElMessage({
        message: "上报成功.",
        type: "success",
      });
    } else {
      ElMessage.error(res.data.msg);
    }
    syncData(currentAuditId);
  });
};

//导出订单
const exportStorefront = () => {
  findStorefrontExcelApi(searchModel).then((res) => {
    const blob = new Blob([res.data]);
    const fileName = "门店报备数据.xls";
    const elink = document.createElement("a"); // 创建a标签
    elink.download = fileName; // 为a标签添加download属性
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click(); // 点击下载
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink); // 释放标签
  });
};

onMounted(() => {
  findStorefront(searchModel);
});
</script>

<style scoped>
:deep(.demo-form-inline) {
  display: grid;
  justify-items: stretch;
  grid-template-columns: repeat(auto-fill, 25%);
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item) {
  width: 90%;
}

:deep(.el-image) {
  width: 600px;
}

.span-location {
  margin-left: 10px;
}

/* :deep(.el-dialog__body) {
    padding: 0px 0px 0px 0px;
} */
</style>
